// DOM 元素
const sections = {
    books: document.getElementById('books-section'),
    users: document.getElementById('users-section'),
    borrowing: document.getElementById('borrowing-section')
};

const modal = document.getElementById('modal');
const modalBody = document.getElementById('modal-body');
const closeBtn = document.querySelector('.close');

// 导航处理
document.querySelectorAll('nav a').forEach(link => {
    link.addEventListener('click', (e) => {
        e.preventDefault();
        const sectionId = e.target.id.split('-')[0];
        showSection(sectionId);
        // 保存当前页面
        localStorage.setItem('currentSection', sectionId);
    });
});

function showSection(sectionId) {
    Object.values(sections).forEach(section => {
        section.style.display = 'none';
    });
    sections[sectionId].style.display = 'block';
}

// 加载状态控制
const loading = document.getElementById('loading');

function showLoading() {
    loading.classList.add('active');
}

function hideLoading() {
    loading.classList.remove('active');
}

// API 请求函数
async function fetchAPI(endpoint, options = {}) {
    showLoading();
    try {
        const baseURL = 'http://localhost:3000/api';
        const response = await fetch(`${baseURL}${endpoint}`, {
            ...options,
            headers: {
                'Content-Type': 'application/json',
                ...options.headers
            }
        });
        if (!response.ok) {
            // 尝试解析错误响应
            const errorData = await response.json();
            throw new Error(errorData.error || `API 请求失败: ${response.statusText}`);
        }
        // 处理 204 No Content 响应
        if (response.status === 204) {
            return null;
        }
        return response.json();
    } finally {
        hideLoading();
    }
}

// 模态框处理
function showModal(content) {
    modalBody.innerHTML = content;
    modal.style.display = 'block';
}

function closeModal() {
    modal.style.display = 'none';
    document.getElementById('register-modal').style.display = 'none';
    document.getElementById('forgot-password-modal').style.display = 'none';
}

// 只处理主模态框的关闭按钮
if (closeBtn) {
    closeBtn.onclick = closeModal;
}

// 初始化
document.addEventListener('DOMContentLoaded', () => {
    checkAuth();
    loadBooks();
    loadUsers();
    loadBorrowings();
    loadBorrowingStats();
    // 显示上次访问的页面，如果没有则默认显示用户管理
    const lastSection = localStorage.getItem('currentSection') || 'users';
    showSection(lastSection);
    initTableSort('books-table', loadBooks);
    initTableSort('users-table', loadUsers);
    initTableSort('borrowing-table', loadBorrowings);
});

// 全局变量
let currentPage = 1;
let totalPages = 1;
let currentUserPage = 1;
let totalUserPages = 1;
let currentBorrowingPage = 1;
let totalBorrowingPages = 1;

// 修改加载图书函数
async function loadBooks(page = 1, sortOptions = {}) {
    try {
        const { sortColumn = 'created_at', sortDirection = 'desc' } = sortOptions;
        const response = await fetchAPI(
            `/books?page=${page}&limit=8&sortColumn=${sortColumn}&sortDirection=${sortDirection}`
        );
        const { data: books, pagination } = response;

        currentPage = pagination.page;
        totalPages = pagination.totalPages;

        const tbody = document.querySelector('#books-table tbody');
        tbody.innerHTML = books.map(book => `
            <tr>
                <td>${book.isbn}</td>
                <td>${book.title}</td>
                <td>${book.author}</td>
                <td>${book.publisher}</td>
                <td>${book.stock}</td>
                <td>
                    <button onclick="editBook(${book.id})" class="button-success">编辑</button>
                    <button onclick="deleteBook(${book.id})" class="button-danger">删除</button>
                </td>
            </tr>
        `).join('');

        // 更新分页信息
        document.getElementById('page-info').textContent = `第 ${currentPage} / ${totalPages} 页`;
        document.getElementById('prev-page').disabled = currentPage === 1;
        document.getElementById('next-page').disabled = currentPage === totalPages;
    } catch (error) {
        alert('加载图书失败：' + error.message);
    }
}

// 分页按钮事件处理
document.getElementById('prev-page').addEventListener('click', () => {
    if (currentPage > 1) {
        loadBooks(currentPage - 1);
    }
});

document.getElementById('next-page').addEventListener('click', () => {
    if (currentPage < totalPages) {
        loadBooks(currentPage + 1);
    }
});

// 导出数据功能
document.getElementById('export-books').addEventListener('click', async () => {
    try {
        showLoading();
        const response = await fetch('http://localhost:3000/api/books/export', {
            headers: {
                'Accept': 'text/csv'
            }
        });

        if (!response.ok) {
            throw new Error('导出失败');
        }

        const blob = await response.blob();
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        const date = new Date().toISOString().split('T')[0];
        a.download = `图书列表_${date}.csv`;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        window.URL.revokeObjectURL(url);
    } catch (error) {
        alert('导出失败：' + error.message);
    } finally {
        hideLoading();
    }
});

// 添加新书
document.getElementById('add-book').addEventListener('click', () => {
    showModal(`
        <h3>添加新书</h3>
        <form id="add-book-form">
            <div class="form-group">
                <label for="isbn">ISBN</label>
                <input type="text" id="isbn" required pattern="[0-9]{13}" title="请输入13位ISBN号">
            </div>
            <div class="form-group">
                <label for="title">书名</label>
                <input type="text" id="title" required>
            </div>
            <div class="form-group">
                <label for="author">作者</label>
                <input type="text" id="author" required>
            </div>
            <div class="form-group">
                <label for="publisher">出版社</label>
                <input type="text" id="publisher">
            </div>
            <div class="form-group">
                <label for="stock">库存</label>
                <input type="number" id="stock" min="0" value="0">
            </div>
            <div class="button-group">
                <button type="submit" class="button-success">添加</button>
                <button type="reset" class="button-danger">重置</button>
            </div>
        </form>
    `);

    document.getElementById('add-book-form').addEventListener('submit', async (e) => {
        e.preventDefault();
        try {
            const formData = {
                isbn: document.getElementById('isbn').value,
                title: document.getElementById('title').value,
                author: document.getElementById('author').value,
                publisher: document.getElementById('publisher').value,
                stock: parseInt(document.getElementById('stock').value) || 0
            };

            const response = await fetchAPI('/books', {
                method: 'POST',
                body: JSON.stringify(formData)
            });

            closeModal();
            loadBooks();
            alert('添加成功！');
        } catch (error) {
            alert('添加失败：' + error.message);
        }
    });
});

// 编辑图书
async function editBook(id) {
    try {
        const book = await fetchAPI(`/books/${id}`);
        showModal(`
            <h3>编辑图书</h3>
            <form id="edit-book-form">
                <div class="form-group">
                    <label for="isbn">ISBN</label>
                    <input type="text" id="isbn" value="${book.isbn}" required>
                </div>
                <div class="form-group">
                    <label for="title">书名</label>
                    <input type="text" id="title" value="${book.title}" required>
                </div>
                <div class="form-group">
                    <label for="author">作者</label>
                    <input type="text" id="author" value="${book.author}" required>
                </div>
                <div class="form-group">
                    <label for="publisher">出版社</label>
                    <input type="text" id="publisher" value="${book.publisher}">
                </div>
                <div class="form-group">
                    <label for="stock">库存</label>
                    <input type="number" id="stock" min="0" value="${book.stock}">
                </div>
                <div class="button-group">
                    <button type="submit" class="button-success">保存</button>
                    <button type="reset" class="button-danger">重置</button>
                </div>
            </form>
        `);

        document.getElementById('edit-book-form').addEventListener('submit', async (e) => {
            e.preventDefault();
            try {
                const formData = {
                    isbn: document.getElementById('isbn').value,
                    title: document.getElementById('title').value,
                    author: document.getElementById('author').value,
                    publisher: document.getElementById('publisher').value,
                    stock: parseInt(document.getElementById('stock').value)
                };

                await fetchAPI(`/books/${id}`, {
                    method: 'PUT',
                    body: JSON.stringify(formData)
                });

                closeModal();
                loadBooks();
                alert('更新成功！');
            } catch (error) {
                alert('更新失败：' + error.message);
            }
        });
    } catch (error) {
        alert('加载图书信息失败：' + error.message);
    }
}

// 删除图书
async function deleteBook(id) {
    if (!confirm('确定要删除这本图书吗？')) {
        return;
    }

    try {
        // 检查图书是否有未归还的借阅记录
        const borrowings = await fetchAPI(`/borrowings/search?book_id=${id}&status=borrowed`);
        if (borrowings && borrowings.length > 0) {
            alert('该图书有未归还的借阅记录，无法删除！');
            return;
        }

        const response = await fetchAPI(`/books/${id}`, {
            method: 'DELETE'
        });
        // response 可能是 null（204 响应），这是正常的

        loadBooks();
        alert('删除成功！');
    } catch (error) {
        alert('删除失败：' + error.message);
    }
}

// 搜索图书
document.getElementById('search-book').addEventListener('input', async (e) => {
    const searchTerm = e.target.value.trim();
    try {
        const books = await fetchAPI(`/books/search?q=${encodeURIComponent(searchTerm)}`);
        const tbody = document.querySelector('#books-table tbody');
        tbody.innerHTML = books.map(book => `
            <tr>
                <td>${book.isbn}</td>
                <td>${book.title}</td>
                <td>${book.author}</td>
                <td>${book.publisher}</td>
                <td>${book.stock}</td>
                <td>
                    <button onclick="editBook(${book.id})" class="button-success">编辑</button>
                    <button onclick="deleteBook(${book.id})" class="button-danger">删除</button>
                </td>
            </tr>
        `).join('');
    } catch (error) {
        alert('搜索失败：' + error.message);
    }
});

// 借阅管理功能
async function loadBorrowingStats() {
    try {
        const stats = await fetchAPI('/borrowings/stats');
        document.getElementById('current-borrowed').textContent = stats.currentBorrowed;
        document.getElementById('soon-expire').textContent = stats.soonExpire;
        document.getElementById('overdue').textContent = stats.overdue;

        // 设置颜色
        if (stats.overdue > 0) {
            document.getElementById('overdue').classList.add('overdue');
        }
        if (stats.soonExpire > 0) {
            document.getElementById('soon-expire').classList.add('warning');
        }
    } catch (error) {
        console.error('加载统计信息失败：', error);
    }
}

// 添加辅助函数
function formatDate(dateString) {
    return new Date(dateString).toLocaleDateString();
}

function getStatusClass(status) {
    return status === 'borrowed' ? 'status-borrowed' : 'status-returned';
}

function formatStatus(status) {
    return status === 'borrowed' ? '借出' : '已还';
}

function getBorrowingRowClass(borrowing) {
    if (borrowing.status !== 'borrowed') {
        return '';
    }

    const today = new Date();
    const returnDate = new Date(borrowing.return_date);
    const sevenDaysLater = new Date(Date.now() + 7 * 24 * 60 * 60 * 1000);

    if (returnDate < today) {
        return 'overdue-row';
    } else if (returnDate <= sevenDaysLater) {
        return 'warning-row';
    }
    return '';
}

// 修改加载借阅记录函数
async function loadBorrowings(page = 1, sortOptions = {}) {
    try {
        const { sortColumn = 'borrow_date', sortDirection = 'desc' } = sortOptions;
        const response = await fetchAPI(
            `/borrowings?page=${page}&limit=5&sortColumn=${sortColumn}&sortDirection=${sortDirection}`
        );
        const { data: borrowings, pagination } = response;

        currentBorrowingPage = pagination.page;
        totalBorrowingPages = pagination.totalPages;

        const tbody = document.querySelector('#borrowing-table tbody');
        tbody.innerHTML = borrowings.map(borrowing => `
            <tr class="${getBorrowingRowClass(borrowing)}">
                <td>${borrowing.id}</td>
                <td>${borrowing.book_title}</td>
                <td>${borrowing.user_name}</td>
                <td>${formatDate(borrowing.borrow_date)}</td>
                <td>${formatDate(borrowing.return_date)}</td>
                <td class="${getStatusClass(borrowing.status)}">${formatStatus(borrowing.status)}</td>
                <td>
                    ${borrowing.status === 'borrowed' ?
                `<button onclick="returnBook(${borrowing.id})" class="button-success">归还</button>` : ''}
                    <button onclick="deleteBorrowing(${borrowing.id})" class="button-danger">删除</button>
                </td>
            </tr>
        `).join('');

        // 更新分页信息
        document.getElementById('page-info-borrowings').textContent = `第 ${currentBorrowingPage} / ${totalBorrowingPages} 页`;
        document.getElementById('prev-page-borrowings').disabled = currentBorrowingPage === 1;
        document.getElementById('next-page-borrowings').disabled = currentBorrowingPage === totalBorrowingPages;

        // 更新统计信息
        loadBorrowingStats();
    } catch (error) {
        alert('加载借阅记录失败：' + error.message);
    }
}

// 借阅分页按钮事件处理
document.getElementById('prev-page-borrowings').addEventListener('click', () => {
    if (currentBorrowingPage > 1) {
        loadBorrowings(currentBorrowingPage - 1);
    }
});

document.getElementById('next-page-borrowings').addEventListener('click', () => {
    if (currentBorrowingPage < totalBorrowingPages) {
        loadBorrowings(currentBorrowingPage + 1);
    }
});

// 导出借阅数据
document.getElementById('export-borrowings').addEventListener('click', async () => {
    try {
        const response = await fetch('http://localhost:3000/api/borrowings/export');
        const blob = await response.blob();
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = 'borrowings.csv';
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        window.URL.revokeObjectURL(url);
    } catch (error) {
        alert('导出失败：' + error.message);
    }
});

// 新增借阅
document.getElementById('new-borrowing').addEventListener('click', async () => {
    try {
        // 获取图书和用户列表
        const books = await fetchAPI('/books');
        const users = await fetchAPI('/users');

        showModal(`
            <h3>新增借阅</h3>
            <form id="add-borrowing-form">
                <div class="form-group">
                    <label for="book_id">图书</label>
                    <select id="book_id" required>
                        <option value="">请选择图书</option>
                        ${books.data.map(book =>
            `<option value="${book.id}" ${book.stock <= 0 ? 'disabled' : ''}>
                                ${book.title} (库存: ${book.stock})
                            </option>`
        ).join('')}
                    </select>
                </div>
                <div class="form-group">
                    <label for="user_id">借阅人</label>
                    <select id="user_id" required>
                        <option value="">请选择借阅人</option>
                        ${users.data.map(user =>
            `<option value="${user.id}">${user.name} (${user.email})</option>`
        ).join('')}
                    </select>
                </div>
                <div class="form-group">
                    <label for="return_date">应还日期</label>
                    <input type="date" id="return_date" required min="${new Date().toISOString().split('T')[0]}">
                </div>
                <div class="button-group">
                    <button type="submit" class="button-success">添加</button>
                    <button type="button" onclick="closeModal()" class="button-danger">取消</button>
                </div>
            </form>
        `);

        document.getElementById('add-borrowing-form').addEventListener('submit', async (e) => {
            e.preventDefault();
            try {
                const formData = {
                    book_id: parseInt(document.getElementById('book_id').value),
                    user_id: parseInt(document.getElementById('user_id').value),
                    return_date: document.getElementById('return_date').value
                };

                await fetchAPI('/borrowings', {
                    method: 'POST',
                    body: JSON.stringify(formData)
                });

                closeModal();
                loadBorrowings();
                loadBorrowingStats();
                alert('借阅成功！');
            } catch (error) {
                alert('借阅失败：' + error.message);
            }
        });
    } catch (error) {
        alert('加载数据失败：' + error.message);
    }
});

// 归还图书功能
async function returnBook(id) {
    if (!confirm('确定要归还这本图书吗？')) {
        return;
    }

    try {
        await fetchAPI(`/borrowings/${id}/return`, {
            method: 'PUT'
        });

        loadBorrowings();
        loadBorrowingStats();
        alert('归还成功！');
    } catch (error) {
        alert('归还失败：' + error.message);
    }
}

// 搜索借阅记录
document.getElementById('search-borrowing').addEventListener('input', async (e) => {
    const searchTerm = e.target.value.trim();
    try {
        const borrowings = await fetchAPI(`/borrowings/search?q=${encodeURIComponent(searchTerm)}`);
        const tbody = document.querySelector('#borrowing-table tbody');
        tbody.innerHTML = borrowings.map(borrowing => `
            <tr>
                <td>${borrowing.id}</td>
                <td>${borrowing.book_title}</td>
                <td>${borrowing.user_name}</td>
                <td>${new Date(borrowing.borrow_date).toLocaleDateString()}</td>
                <td>${new Date(borrowing.return_date).toLocaleDateString()}</td>
                <td>${borrowing.status === 'borrowed' ? '借出' : '已还'}</td>
                <td>
                    ${borrowing.status === 'borrowed' ?
                `<button onclick="returnBook(${borrowing.id})" class="button-success">归还</button>` :
                '已归还'}
                </td>
            </tr>
        `).join('');
    } catch (error) {
        alert('搜索失败：' + error.message);
    }
});

// 用户管理功能
async function loadUsers(page = 1, sortOptions = {}) {
    try {
        const { sortColumn = 'created_at', sortDirection = 'desc' } = sortOptions;
        const response = await fetchAPI(
            `/users?page=${page}&limit=8&sortColumn=${sortColumn}&sortDirection=${sortDirection}`
        );
        const { data: users, pagination } = response;

        currentUserPage = pagination.page;
        totalUserPages = pagination.totalPages;

        const tbody = document.querySelector('#users-table tbody');
        tbody.innerHTML = users.map(user => `
            <tr>
                <td>${user.id}</td>
                <td>${user.name}</td>
                <td>${user.email}</td>
                <td>${user.phone || '-'}</td>
                <td>
                    <button onclick="editUser(${user.id})" class="button-success">编辑</button>
                    <button onclick="deleteUser(${user.id})" class="button-danger">删除</button>
                </td>
            </tr>
        `).join('');

        // 更新分页信息
        document.getElementById('page-info-users').textContent = `第 ${currentUserPage} / ${totalUserPages} 页`;
        document.getElementById('prev-page-users').disabled = currentUserPage === 1;
        document.getElementById('next-page-users').disabled = currentUserPage === totalUserPages;
    } catch (error) {
        alert('加载用户失败：' + error.message);
    }
}

// 用户分页按钮事件处理
document.getElementById('prev-page-users').addEventListener('click', () => {
    if (currentUserPage > 1) {
        loadUsers(currentUserPage - 1);
    }
});

document.getElementById('next-page-users').addEventListener('click', () => {
    if (currentUserPage < totalUserPages) {
        loadUsers(currentUserPage + 1);
    }
});

// 导出用户数据
document.getElementById('export-users').addEventListener('click', async () => {
    try {
        const response = await fetch('http://localhost:3000/api/users/export');
        const blob = await response.blob();
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = 'users.csv';
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        window.URL.revokeObjectURL(url);
    } catch (error) {
        alert('导出失败：' + error.message);
    }
});

// 添加用户
document.getElementById('add-user').addEventListener('click', () => {
    showModal(`
        <h3>添加用户</h3>
        <form id="add-user-form">
            <div class="form-group">
                <label for="name">姓名</label>
                <input type="text" id="name" required>
            </div>
            <div class="form-group">
                <label for="email">邮箱</label>
                <input type="email" id="email" required>
            </div>
            <div class="form-group">
                <label for="phone">电话</label>
                <input type="tel" id="phone" pattern="[0-9]{11}" title="请输入11位手机号码">
            </div>
            <div class="form-group">
                <p class="form-note">注：默认密码为 123456</p>
            </div>
            <div class="button-group">
                <button type="submit" class="button-success">添加</button>
                <button type="reset" class="button-danger">重置</button>
            </div>
        </form>
    `);

    document.getElementById('add-user-form').addEventListener('submit', async (e) => {
        e.preventDefault();
        try {
            const formData = {
                name: document.getElementById('name').value,
                email: document.getElementById('email').value,
                phone: document.getElementById('phone').value || ''
            };

            const response = await fetchAPI('/users', {
                method: 'POST',
                body: JSON.stringify(formData)
            });

            closeModal();
            loadUsers();
            alert('添加成功！默认密码为：123456');
        } catch (error) {
            alert('添加失败：' + error.message);
        }
    });
});

// 编辑用户
async function editUser(id) {
    try {
        const user = await fetchAPI(`/users/${id}`);
        showModal(`
            <h3>编辑用户</h3>
            <form id="edit-user-form">
                <input type="hidden" id="edit-user-id" value="${user.id}">
                <div class="form-group">
                    <label for="edit-name">姓名</label>
                    <input type="text" id="edit-name" value="${user.name}" required>
                </div>
                <div class="form-group">
                    <label for="edit-email">邮箱</label>
                    <input type="email" id="edit-email" value="${user.email}" required>
                </div>
                <div class="form-group">
                    <label for="edit-phone">电话</label>
                    <input type="tel" id="edit-phone" value="${user.phone || ''}" pattern="[0-9]{11}" title="请输入11位手机号码">
                </div>
                <div class="form-group">
                    <label for="edit-password">新密码</label>
                    <input type="password" id="edit-password" placeholder="留空表示不修改密码">
                </div>
                <div class="form-group">
                    <label for="edit-confirm-password">确认新密码</label>
                    <input type="password" id="edit-confirm-password" placeholder="留空表示不修改密码">
                </div>
                <div class="button-group">
                    <button type="submit" class="button-success">保存</button>
                    <button type="reset" class="button-danger">重置</button>
                </div>
            </form>
        `);

        document.getElementById('edit-user-form').addEventListener('submit', async (e) => {
            e.preventDefault();
            try {
                const password = document.getElementById('edit-password').value;
                const confirmPassword = document.getElementById('edit-confirm-password').value;

                // 如果输入了密码，检查两次输入是否一致
                if (password || confirmPassword) {
                    if (password !== confirmPassword) {
                        alert('两次输入的密码不一致');
                        return;
                    }
                }

                const formData = {
                    name: document.getElementById('edit-name').value,
                    email: document.getElementById('edit-email').value,
                    phone: document.getElementById('edit-phone').value || '',
                    password: password // 如果密码为空，后端将忽略密码更新
                };

                await fetchAPI(`/users/${id}`, {
                    method: 'PUT',
                    body: JSON.stringify(formData)
                });

                closeModal();
                loadUsers();
                alert('更新成功！');
            } catch (error) {
                alert('更新失败：' + error.message);
            }
        });
    } catch (error) {
        alert('获取用户信息失败：' + error.message);
    }
}

// 删除用户
async function deleteUser(id) {
    if (!confirm('确定要删除这个用户吗？')) {
        return;
    }

    try {
        // 检查用户是否有未归还的借阅记录
        const borrowings = await fetchAPI(`/borrowings/search?user_id=${id}&status=borrowed`);
        if (borrowings && borrowings.length > 0) {
            alert('该用户有未归还的借阅记录，无法删除！');
            return;
        }

        await fetchAPI(`/users/${id}`, {
            method: 'DELETE'
        });

        loadUsers();
        alert('删除成功！');
    } catch (error) {
        alert('删除失败：' + error.message);
    }
}

// 搜索用户
document.getElementById('search-user').addEventListener('input', async (e) => {
    const searchTerm = e.target.value.trim();
    try {
        const users = await fetchAPI(`/users/search?q=${encodeURIComponent(searchTerm)}`);
        const tbody = document.querySelector('#users-table tbody');
        tbody.innerHTML = users.map(user => `
            <tr>
                <td>${user.id}</td>
                <td>${user.name}</td>
                <td>${user.email}</td>
                <td>${user.phone || '-'}</td>
                <td>
                    <button onclick="editUser(${user.id})" class="button-success">编辑</button>
                    <button onclick="deleteUser(${user.id})" class="button-danger">删除</button>
                </td>
            </tr>
        `).join('');
    } catch (error) {
        alert('搜索失败：' + error.message);
    }
});

// 表格排序功能
function initTableSort(tableId, loadData) {
    const table = document.getElementById(tableId);
    if (!table) return;

    const headers = table.querySelectorAll('th[data-field]'); // 只选择有 data-field 属性的表头
    let currentSort = { column: null, direction: 'asc' };

    headers.forEach((header) => {
        // 添加排序指示器的样式
        header.classList.add('sortable');

        header.addEventListener('click', () => {
            // 清除其他列的排序状态
            headers.forEach(h => {
                h.classList.remove('sort-asc', 'sort-desc');
            });

            // 更新排序状态
            if (currentSort.column === header.dataset.field) {
                currentSort.direction = currentSort.direction === 'asc' ? 'desc' : 'asc';
            } else {
                currentSort.column = header.dataset.field;
                currentSort.direction = 'asc';
            }

            // 添加排序指示器
            header.classList.add(`sort-${currentSort.direction}`);

            // 重新加载数据
            loadData(1, {
                sortColumn: currentSort.column,
                sortDirection: currentSort.direction
            });
        });
    });
}

// 检查登录状态
function checkAuth() {
    const user = JSON.parse(localStorage.getItem('user'));
    if (!user) {
        document.getElementById('app').style.display = 'none';
        document.getElementById('login-page').style.display = 'flex';
    } else {
        document.getElementById('app').style.display = 'block';
        document.getElementById('login-page').style.display = 'none';
    }
}

// 登录表单处理
document.getElementById('login-form').addEventListener('submit', async (e) => {
    e.preventDefault();
    try {
        const formData = {
            email: document.getElementById('login-email').value,
            password: document.getElementById('login-password').value
        };

        const response = await fetchAPI('/auth/login', {
            method: 'POST',
            body: JSON.stringify(formData)
        });

        localStorage.setItem('user', JSON.stringify(response));
        // 清空登录表单
        document.getElementById('login-form').reset();
        checkAuth();
        // 登录成功后加载用户管理页面
        showSection('users');
        localStorage.setItem('currentSection', 'users');
        loadUsers();
    } catch (error) {
        alert('登录失败：' + error.message);
    }
});

// 显示注册表单
function showRegisterForm() {
    document.getElementById('register-modal').style.display = 'block';
}

// 注册表单处理
document.getElementById('register-form').addEventListener('submit', async (e) => {
    e.preventDefault();
    try {
        // 获取并验证表单数据
        const name = document.getElementById('register-name').value.trim();
        const email = document.getElementById('register-email').value.trim();
        const password = document.getElementById('register-password').value;
        const confirmPassword = document.getElementById('register-confirm-password').value;
        const phone = document.getElementById('register-phone').value.trim();

        // 验证姓名
        if (!name) {
            alert('请输入姓名');
            return;
        }

        // 验证邮箱
        if (!email) {
            alert('请输入邮箱');
            return;
        }

        // 验证邮箱格式
        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        if (!emailRegex.test(email)) {
            alert('请输入正确的邮箱格式');
            return;
        }

        if (password !== confirmPassword) {
            alert('两次输入的密码不一致');
            return;
        }

        // 验证密码长度
        if (password.length < 6 || password.length > 20) {
            alert('密码长度必须在6-20位之间');
            return;
        }

        // 验证手机号格式
        if (phone && !/^1[3-9]\d{9}$/.test(phone)) {
            alert('请输入正确的手机号码');
            return;
        }

        const formData = {
            name,
            email,
            phone: phone || '',
            password: password
        };

        await fetchAPI('/auth/register', {
            method: 'POST',
            body: JSON.stringify(formData)
        });

        // 清空表单
        document.getElementById('register-form').reset();
        closeModal();
        alert('注册成功，请登录');
    } catch (error) {
        alert(error.message);
    }
});

// 修改取消按钮的处理函数
function cancelRegister() {
    document.getElementById('register-form').reset();  // 清空表单
    closeModal();
}

// 退出登录
document.getElementById('logout').addEventListener('click', (e) => {
    e.preventDefault();
    localStorage.removeItem('user');
    // 清空登录表单
    document.getElementById('login-form').reset();
    checkAuth();
});

// 删除借阅记录
async function deleteBorrowing(id) {
    if (!confirm('确定要删除这条借阅记录吗？')) {
        return;
    }

    try {
        await fetchAPI(`/borrowings/${id}`, {
            method: 'DELETE'
        });

        loadBorrowings();
        loadBorrowingStats();
        alert('删除成功！');
    } catch (error) {
        alert('删除失败：' + error.message);
    }
}

// 显示忘记密码表单
document.getElementById('forgot-password').addEventListener('click', (e) => {
    e.preventDefault();
    document.getElementById('forgot-password-modal').style.display = 'block';
});

// 取消重置密码
function cancelResetPassword() {
    document.getElementById('forgot-password-form').reset();
    document.getElementById('forgot-password-modal').style.display = 'none';
}

// 处理重置密码表单提交
document.getElementById('forgot-password-form').addEventListener('submit', async (e) => {
    e.preventDefault();
    try {
        const password = document.getElementById('reset-password').value;
        const confirmPassword = document.getElementById('reset-confirm-password').value;

        if (password !== confirmPassword) {
            alert('两次输入的密码不一致');
            return;
        }

        const formData = {
            email: document.getElementById('reset-email').value,
            phone: document.getElementById('reset-phone').value,
            newPassword: password
        };

        await fetchAPI('/auth/reset-password', {
            method: 'POST',
            body: JSON.stringify(formData)
        });

        // 清空表单
        document.getElementById('forgot-password-form').reset();
        document.getElementById('forgot-password-modal').style.display = 'none';
        alert('密码重置成功，请使用新密码登录');
    } catch (error) {
        alert('密码重置失败：' + error.message);
    }
}); 